package com.meitianhui.convenitenbuy.module.home.adapter;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.view.View;
import android.webkit.JavascriptInterface;

import com.bumptech.glide.Glide;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.module.home.ui.activity.web.EdinburghWebViewActivity;
import com.meitianhui.convenitenbuy.util.EmptyUtil;
import com.meitianhui.convenitenbuy.util.LogUtils;
import com.meitianhui.convenitenbuy.util.StringUtils;
import com.meitianhui.convenitenbuy.util.SystemUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.dialog.ShareDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * “会过”模块改为 h5 页面，因此 WebView 的设置只能放在 HomeAdapter 中。
 * 为了防止 HomeAdapter 变得过分臃肿，将 JsBridge/ShareClickListener 等单独拿出来作为一个类。
 * Created by Liam on 2018/5/29.
 */

public class HuiGuoWebPageHelper {

    private static final int SHARE_TYPE_WECHAT_FRIENDS_CIRCLE = 1;
    private static final int SHARE_TYPE_WECHAT_FRIEND = 2;
    private static final int SHARE_TYPE_QQ_FRIEND = 3;
    private static final int SHARE_TYPE_QQ_ZONE = 4;

    private static final String SAVED_IMAGE_NAME = "tobe_share_";
    private static int index = 0;

    private Context context;
    private Handler handler = new Handler();
    private ShareDialog shareDialog = null;
    private ShareDialog.OnShareClickListener shareClickListener = null;
    // 待分享图片的路径。
    private List<String> imageUrls;
    private String description = null;

    public HuiGuoWebPageHelper(Context context) {
        this.context = context;
        this.imageUrls = new ArrayList<>();
    }

    /**
     * 点击待分享的9个商品图片中的一张，跳转到对应商品的详情页面。
     * @param json 商品参数
     */
    @JavascriptInterface
    public void clickSharedImage(String json) {
        if (EmptyUtil.isEmpty(json)) return;
        String goodsId = null;
        String dataSource = null;
        try {
            JSONObject jsonObject = new JSONObject(json);
            goodsId = jsonObject.getString("goods_id");
            dataSource = jsonObject.getString("data_source");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (EmptyUtil.isEmpty(goodsId)) {
            LogUtils.e("GoodsId is null or empty.");
            return;
        }

        final String finalGoodsId = goodsId;
        final String finalDataSource = StringUtils.nullToEmpty(dataSource);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(context, EdinburghWebViewActivity.class);
                String title;
                String pattern;
                switch (finalDataSource) {
                    case "meitianhui":
                        title = "自营";
                        pattern = "h5/c/payback/ziying-detail?goods_id=";
                        break;
                    case "huiguo":
                        title = "会过";
                        pattern = "h5/c/payback/huiguo-detail?goods_id=";
                        break;
                    default:
                        title = "淘淘领";
                        pattern = "h5/c/payback/detail?goods_id=";
                }

                if (InfoProvider.getLoginStatus(context)) {
                    intent.putExtra("url", Constants.HOST + pattern + finalGoodsId
                            + "&mi=" + InfoProvider.getUserToken(context).getMember_id()
                            + "&mobile=" + InfoProvider.getUserToken(context).getMobile()
                            + "&bind=1");
                } else {
                    intent.putExtra("url", Constants.HOST + pattern + finalGoodsId
                            + "&bind=1");
                }
                intent.putExtra("title", title);
                intent.putExtra("is_second", true);
                context.startActivity(intent);
            }
        }, 0);
    }

    /**
     * 分享9个商品图片。
     * @param json 9个商品参数
     */
    @JavascriptInterface
    public void shareNineImages(String json) {
        if (EmptyUtil.isEmpty(json)) return;
        if (EmptyUtil.isNotEmpty(imageUrls)) imageUrls.clear();
        if (EmptyUtil.isNotEmpty(description)) description = null;

        // Get shared images.
        try {
            JSONArray jsonArray = new JSONArray(json);
            JSONObject jsonObject;
            String imageUrl;
            int len = jsonArray.length();

            for (int i = 0; i < len; i++) {
                jsonObject = jsonArray.getJSONObject(i);
                if (EmptyUtil.isEmpty(description)) {
                    description = jsonObject.optString("share_name");
                }
                imageUrl = jsonObject.optString("share_image_url");
                if (EmptyUtil.isNotEmpty(imageUrl)) {
                    imageUrls.add(imageUrl);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (EmptyUtil.isEmpty(imageUrls)) return;
        // Share dialog.
        shareDialog = new ShareDialog(context, getShareClickListener(),
                Constants.TYPE_NO_SHOW_WXMINI_SHARE);
        shareDialog.show();
    }

    private ShareDialog.OnShareClickListener getShareClickListener() {
        if (shareClickListener != null) {
            return shareClickListener;
        }
        initShareClickListener();
        return shareClickListener;
    }

    // 初始化 ShareClickListener.
    private void initShareClickListener() {
        shareClickListener = new ShareDialog.OnShareClickListener() {
            @Override
            public void FriendCircle(View v) {
                if (!isWeiXinInstalled()) {
                    TipUtils.showToastLong(context, context.getString(
                            R.string.wallet_change_recharge_order_wechat_uninstall));
                    return;
                }

                pleaseWait();
                startShare(SHARE_TYPE_WECHAT_FRIENDS_CIRCLE);
                // startShareImages(1);
                shareDialog.dismiss();
            }

            @Override
            public void WeChatFriends(View v) {
                if (!isWeiXinInstalled()) {
                    TipUtils.showToastLong(context, context.getString(
                            R.string.wallet_change_recharge_order_wechat_uninstall));
                    return;
                }

                pleaseWait();
                startShare(SHARE_TYPE_WECHAT_FRIEND);
                // startShareImages(0);
                shareDialog.dismiss();
            }

            @Override
            public void QQFriends(View v) {

            }

            @Override
            public void QQZone(View v) {

            }

            @Override
            public void WxMini(View v) {
                // WeiXin mini program.
            }
        };
    }

    /**
     * 生成对应的 Intent 对象。
     * @param type Intent 类型。1.微信朋友圈 2.微信好友 3.QQ好友 4.QQ空间
     */
    private void startShare(int type) {
        index = 0;
        ArrayList<Uri> imageFileUris = downloadImages();

        Intent intent = new Intent();
        ComponentName comp = null;
        switch (type) {
            case SHARE_TYPE_WECHAT_FRIENDS_CIRCLE:
                comp = new ComponentName("com.tencent.mm",
                        "com.tencent.mm.ui.tools.ShareToTimeLineUI");
                break;
            case SHARE_TYPE_WECHAT_FRIEND:
                comp = new ComponentName("com.tencent.mm",
                        "com.tencent.mm.ui.tools.ShareImgUI");
                break;
            case SHARE_TYPE_QQ_FRIEND:
                break;
            case SHARE_TYPE_QQ_ZONE:
                break;
            default:
                break;
        }

        intent.setComponent(comp);
        if (description != null) {
            intent.putExtra("Kdescription", description);
        }
        intent.setAction(Intent.ACTION_SEND_MULTIPLE);
        intent.setType("image/*");
        intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageFileUris);
        context.startActivity(intent);
    }

    public void startShareImages(int flag) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                ArrayList<Uri> imageFileUris = new ArrayList<>();
                for (int i = 0; i < imageUrls.size(); i++) {
                    File file = saveImageToSdCard(context, imageUrls.get(i));
                    imageFileUris.add(Uri.fromFile(file));
                }

                Intent intent = new Intent();
                ComponentName comp;
                if (flag == 0) {
                    comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
                } else {
                    comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
                    intent.putExtra("Kdescription", description);
                }
                intent.setComponent(comp);
                intent.setAction(Intent.ACTION_SEND_MULTIPLE);
                intent.setType("image/*");
                intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageFileUris);
                context.startActivity(intent);
            }
        }).start();
    }

    /**
     * Show toast before jumping to WeChat/QQ Application.
     */
    private void pleaseWait() {
        TipUtils.showToastLong(context, "请稍等...");
    }

    /**
     * 是否安装了微信。
     */
    private boolean isWeiXinInstalled() {
        return SystemUtils.isAppInstalled(context, "com.tencent.mm");
    }

    /**
     * 是否安装了QQ。
     */
    private boolean isQQInstalled() {
        return SystemUtils.isAppInstalled(context, "com.tencent.mobileqq");
    }

    /**
     * 下载图片到本地。
     */
    private ArrayList<Uri> downloadImages() {
        ArrayList<Uri> imageFileUris = new ArrayList<>();

        for (String url : imageUrls) {
            Bitmap bitmap = null;
            try {
                bitmap = Glide.with(context).asBitmap().load(url).submit().get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }

            if (bitmap != null) {
                File file = saveBitmapInSdCard(context, bitmap);
                imageFileUris.add(Uri.fromFile(file));
            }
        }

        return imageFileUris;
    }

    private static File saveBitmapInSdCard(Context context, Bitmap bitmap) {
        File file = createFilepath(context);
        OutputStream out = null;

        try {
            out = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            return file;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // e.printStackTrace();
                    // swallow
                }
            }
        }
        return null;
    }

    private static File saveImageToSdCard(Context context, String imageUrl) {
        File file = null;
        HttpURLConnection conn = null;

        try {
            file = createFilepath(context);

            URL url = new URL(imageUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(20000);
            conn.setReadTimeout(20000);
            InputStream is = conn.getInputStream();
            Bitmap bitmap = BitmapFactory.decodeStream(is);

            OutputStream outStream = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            is.close();
            return file;

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return null;
    }

    private static File createFilepath(Context context) {
        index++;
        String imageFilename = SAVED_IMAGE_NAME + index + ".jpg";
        File file = new File(context.getExternalCacheDir(), imageFilename);

        if (file.exists()) {
            boolean delResult = file.delete();
            if (!delResult) {
                LogUtils.e("删除文件失败");
            }
        }
        return file;
    }

    /**
     * 下载图片成功后的回调。
     */
    public interface DownloadCompletedCallback {
        void callback(ArrayList<Uri> uris);
    }

}
